package top.wangjiu.reactive.rpc.autoconfigure.server;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.server.WebServerException;
import top.wangjiu.reactive.rpc.config.ServerConfiguration;
import top.wangjiu.reactive.rpc.server.RpcServer;

/**
 * @ClassName RpcApplicationServer
 * @Description TODO
 * @Author wangjiu
 * @Date 2021/8/11 5:35 下午
 */
public class RpcApplicationServer implements WebServer {

    private static final Log log = LogFactory.getLog(RpcServer.class);

    private volatile RpcServer rpcServer;

    public RpcApplicationServer(ServerConfiguration configuration){
        rpcServer = new RpcServer(configuration);
    }

    @Override
    public void start() throws WebServerException {
        rpcServer.start();
        startDaemonAwaitThread();
    }

    @Override
    public void stop() throws WebServerException {
        rpcServer.stop();
    }

    @Override
    public int getPort() {
        return rpcServer.getPort();
    }

    private void startDaemonAwaitThread() {
        Thread awaitThread = new Thread("server") {
            @Override
            public void run() {
                try {
                    rpcServer.waitStop();
                } catch (InterruptedException e) {
                    log.error("server wait stop error",e);
                }
            }
        };
        awaitThread.setContextClassLoader(getClass().getClassLoader());
        awaitThread.setDaemon(false);
        awaitThread.start();
    }

}
